using ColorFillGame.API.Hubs;
using ColorFillGame.Application.Commands;
using ColorFillGame.Application.Queries;
using ColorFillGame.Domain.Repositories;
using ColorFillGame.Domain.Services;
using ColorFillGame.Infrastructure.Data;
using ColorFillGame.Infrastructure.Repositories;
using MediatR;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

// 配置CORS
builder.Services.AddCors(options =>
{
    options.AddPolicy("AllowFrontend", policy =>
    {
        policy.WithOrigins("http://localhost:5174", "http://localhost:5173")
              .AllowAnyMethod()
              .AllowAnyHeader()
              .AllowCredentials();
    });
});

// 添加SignalR
builder.Services.AddSignalR();

// 添加控制器
builder.Services.AddControllers();

// 添加Swagger/OpenAPI
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

// 添加MediatR
builder.Services.AddMediatR(cfg => cfg.RegisterServicesFromAssembly(typeof(ICommand).Assembly));
builder.Services.AddMediatR(cfg => cfg.RegisterServicesFromAssembly(typeof(IQuery<>).Assembly));

// 添加数据库上下文
builder.Services.AddDbContext<AppDbContext>(options =>
    options.UseNpgsql(builder.Configuration.GetConnectionString("DefaultConnection")));

// 添加领域服务
builder.Services.AddScoped<IGameService, GameService>();

// 添加仓储
builder.Services.AddScoped<IGameRepository, GameRepository>();
builder.Services.AddScoped<IPlayerRepository, PlayerRepository>();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

// 使用CORS策略
app.UseCors("AllowFrontend");

// 使用授权
app.UseAuthorization();

// 映射控制器路由
app.MapControllers();

// 映射Hub路由
app.MapHub<GameHub>("/hubs/game");

app.Run();
